package org.heydr.common.http;

import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringUtils {
	private static final Logger log = LoggerFactory.getLogger(StringUtils.class);
	
	/**
	 * 转换16进制为字符
	 * 
	 * @param source
	 * @return
	 */
	public static String hexToChar(String source) {
		String flag = "&#";
		if (null == source || "".equals(source)) {
			return "";
		}

		if (source.indexOf(flag) >= 0) {
			StringBuffer newValue = new StringBuffer();
			StringTokenizer st = new StringTokenizer(source, ";");
			while (st.hasMoreElements()) {
				String value = "" + st.nextElement();
				if ("".equals(value)) {
					continue;
				}
				int flagPosition = value.indexOf(flag);

				if (flagPosition >= 0) {//
					if (flagPosition > 0) {// 标志位前还有非unicode字符
						String others = value.substring(0, flagPosition);
						newValue.append(others);
					}
					value = value.substring(flagPosition + flag.length());
					boolean is16Int = false;
					if (value.startsWith("x")) {
						value = value.replace("x", "");
						is16Int = true;
					}

					try {
						int OctalInt = 0;
						if (is16Int) {
							OctalInt = Integer.parseInt(value, 16);
						} else {
							OctalInt = Integer.parseInt(value);
						}

						// // old
						// if (value.length() >= 3 && value.length() <= 4)
						// OctalInt = Integer.parseInt(value, 16);
						// else
						// OctalInt = Integer.parseInt(value);
						newValue.append(String.valueOf((char) OctalInt));
					} catch (NumberFormatException e) {// 过滤unicode编码中包含的&nbsp;等符号
						// add by norby
						continue;
					}
				} else {
					newValue.append(value);
				}
			}

			source = newValue.toString();
		}
		return source;
	}

	/**
	 * 将字符串中的16进制编码字符转换为普通字符串，支持 以下几种十六进制格式："\x3d", "&#3d;"
	 * 
	 * @param str
	 * @return
	 */
	public static String hexToStr(String str) {
		Pattern p = Pattern.compile("\\\\x.{2}");
		Matcher m = p.matcher(str);
		String subStr = null;
		while (m.find()) {
			subStr = m.group(0);
			str = str.replace(subStr, subStr.replace("\\x", "&#x") + ";");
		}
		str = StringEscapeUtils.unescapeHtml(str);
		return str;
	}


	/**
	 * 获取文件后缀
	 * 
	 * @param fileName
	 * @return 文件后缀
	 */
	public static String getFileExt(String fileName) {
		if (fileName == null || fileName.equals("")) {
			return fileName;
		}

		String ext = fileName.substring(fileName.lastIndexOf(".") + 1).trim()
				.toLowerCase();

		return ext;
	}

	/**
	 * 不区大小写replace
	 * 
	 * @param source
	 *            源串
	 * @param oldStr
	 *            被替换的子串
	 * @param newStr
	 *            替换的子串
	 * @return 替换之后的源串
	 */
	public static String replaceIgnoreCase(String source, String oldStr,
			String newStr) {
		if (source == null || source.length() == 0 || oldStr == null
				|| oldStr.length() == 0 || newStr == null) {
			return source;
		}

		String sourceLower = source.toLowerCase();
		String oldStrLower = oldStr.toLowerCase();

		if (sourceLower.indexOf(oldStrLower) == -1) {
			return source;
		}

		int oldLen = oldStrLower.length();
		String subStr = null;
		Set<String> occurOldStrSet = new HashSet<String>();
		int i = 0;
		while ((i = sourceLower.indexOf(oldStrLower, i)) != -1) {
			subStr = source.substring(i, i + oldLen);
			if (!occurOldStrSet.contains(subStr)) {
				occurOldStrSet.add(subStr);
			}
			i = i + oldLen;
		}
		for (String old : occurOldStrSet) {
			source = source.replace(old, newStr);
		}

		return source;
	}

	/**
	 * 检测是否为全汉字字符串
	 * 
	 * @param str
	 * @return 注：null和空串，则返回false
	 */
	public static boolean isChineseStr(String str) {
		if (str == null || str.length() == 0) {
			return false;
		}

		char c;
		int len = str.length();
		for (int i = 0; i < len; i++) {
			c = str.charAt(i);
			if (!isChinese(c)) {
				return false;
			}
		}

		return true;
	}


	/**
	 * 检测是否为汉字字符
	 * 
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {
		return c <= 40869 && c >= 19968;
	}

	/**
	 * 检查字符串是否为null，如果是就返回空串，否则返回本身
	 * 
	 * @param str
	 * @return
	 */
	public static String checkNull(String str) {
		if (str == null) {
			str = "";
		}

		return str;
	}

	/**
	 * 检查字符串是否为null或空串，如果是就返回"0"，否则返回本身
	 * 
	 * @param str
	 * @return
	 */
	public static String checkNumber(String str) {
		if (null == str || "".equals(str)) {
			return "0";
		} else {
			return str;
		}
	}
	
	/**
	 * 检测是否为字母
	 * 
	 * @param c
	 * @return 是:true,否:false
	 */
	public static boolean isLetter(char c) {
		return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
	}
	
	/**
	 * 是否为数字
	 * 
	 * @param c
	 * @return 是:true,否:false
	 */
	public static boolean isDigit(char c) {
		return ((c >= '0' && c <= '9'));
	}
	
	/**
	 * 用英文空格分开字母和数字
	 * 
	 * @param str
	 * @return 分开后的结果
	 */
	public static String breakAlphabetDigit(String str) {
		if (str == null || str.length() <= 1) {
			return str;
		}

		int len = str.length();
		StringBuilder sb = new StringBuilder(len + 5);
		sb.append(str.charAt(0));
		for (int i = 1; i < len; i++) {
			char c = str.charAt(i);
			char lastC = str.charAt(i - 1);
			if ((isLetter(c) && isDigit(lastC)) || isDigit(c)
					&& isLetter(lastC)) {
				sb.append(' ').append(c);
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}

	public static String md5(String str) {
		if (str == null) {
			return null;
		}
		return DigestUtils.md5Hex(
				org.apache.commons.codec.binary.StringUtils.getBytesUtf8(str))
				.toLowerCase();
	}

	
}
